package com.wanghua.mall.ware.listener;

import com.rabbitmq.client.Channel;
import com.wanghua.common.dto.mq.OrderDto;
import com.wanghua.common.dto.mq.StockLockedDto;
import com.wanghua.mall.ware.config.WareRabbitMQConfig;
import com.wanghua.mall.ware.service.WareSkuService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 监听库存变化
 *
 * @author wanghua
 * @create 2021-09-10 15:01
 */
@Component
@RabbitListener(queues = WareRabbitMQConfig.STOCK_RELEASE_QUEUE_NAME)
public class StockListener {

    @Resource
    private WareSkuService wareSkuService;


    /**
     * 1、库存自动解锁
     * 下订单成功，库存锁定成功，接下来的业务调用失败，导致订单回滚。之前锁定的库存就要自动解锁
     * <p>
     * <p>
     * 2、订单失败
     * 库存锁定失败
     * <p>
     * 只要解锁库存的消息失败，一定要告诉服务解锁失败
     *
     * @param message        message
     * @param stockLockedDto stockLockedDto
     * @param channel        channel
     */
    @RabbitHandler
    public void releaseLockStock(Message message, StockLockedDto stockLockedDto, Channel channel) {
        boolean b = wareSkuService.releaseLockStock(stockLockedDto);
        if (b) {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            try {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    /**
     * 订单关闭，准备解锁库存
     * @param message
     * @param orderDto
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderClose(Message message, OrderDto orderDto, Channel channel) throws IOException {
        System.out.println("订单关闭，准备解锁库存");
        try {
            wareSkuService.releaseLockStock(orderDto);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }

    }

}
